package www.golf.web.gonwubu;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.python.core.exceptions;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Button;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;
import org.zkoss.zul.Listbox;

import www.golf.ibatis.bean.A_project;
import www.golf.ibatis.bean.A_projectShow;
import www.golf.ibatis.bean.Projectset;
import www.golf.ibatis.bean.Subcontractor;
import www.golf.web.session.WebSession;
import www.golf.web.util.UtilListbox;
import www.golf.web.util.UtilZKObject;

public class AgreementControl extends WebSession{
	UtilZKObject ZKObj =new UtilZKObject(this);
	UtilListbox lb= new UtilListbox();
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	public void initialize() {
		List list=null;
		try {
			list = (List)dbSession().queryForList("Agreement.selectAgreement");
			dbSessionClose();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		lb.setComponentData(this, "grid", list,dataRender());
		set_power();
		setListData();
	}
	public void searchData(){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("project", (ZKObj.getValue("project").equals(""))?null:Integer.parseInt(ZKObj.getValue("project")));
		map.put("project_set", (ZKObj.getValue("project_set").equals(""))?null:Integer.parseInt(ZKObj.getValue("project_set")));
		map.put("sub", (ZKObj.getValue("sub").equals(""))?null:Integer.parseInt(ZKObj.getValue("sub")));
		map.put("sdate1", parserDate("sdate1"));
		map.put("sdate2", parserDate("sdate2"));
		map.put("edate1", parserDate("edate1"));
		map.put("edate2", parserDate("edate1"));
		List list=null;
		try {
			list = (List)dbSession().queryForList("Agreement.selectAgreement",map);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		lb.setComponentData(this, "grid", list,dataRender());
	}
	public void set_power(){
		boolean group=false;
		for(int i=0;i<getUserGroup().length;i++){
			if(getUserGroup()[i]==2||getUserGroup()[i]<0){
				group=true;
			}
		}
		if(getUserPower()<=13&&group){
			getFellow("add").setVisible(true);
			getFellow("edit").setVisible(true);
		}
	}
	public ListitemRenderer dataRender(){
		 return new ListitemRenderer(){
				public void render(Listitem item, Object data) throws Exception {
					A_projectShow form = (A_projectShow) data;
					
					Listcell Serial = new Listcell();
					Serial.setLabel(form.getSerial_num());
					Serial.setParent(item);	
					
					Listcell name = new Listcell();
					name.setLabel(form.getName());
					name.setParent(item);		
					
					Listcell subcontractor = new Listcell();
					subcontractor.setLabel(form.getSubcontractor_name());
					subcontractor.setAttribute("pid", form.getSubcontractor_id());
					subcontractor.setParent(item);		
					
					Listcell note = new Listcell();
					if(form.getNote().equals("")||form.getNote()==null){
						note.setLabel(form.getNote());
					}else{
						Label lb=new Label("检视");
						lb.setStyle("color:blue;TEXT-DECORATION:UNDERLINE;");
						lb.setTooltiptext(form.getNote());
						lb.setParent(note);
					}
					note.setParent(item);	
					
					Listcell signer = new Listcell();
					signer.setLabel(form.getSigner_name());
					signer.setAttribute("pid", form.getSigner());
					signer.setParent(item);	
					
					Listcell edate = new Listcell();
					edate.setLabel(setDate(form.getS_date()));
					edate.setParent(item);	
					
					Listcell sdate = new Listcell();
					sdate.setLabel(setDate(form.getE_date()));
					sdate.setParent(item);	
					
					Listcell cdate = new Listcell();
					cdate.setLabel(setDate(form.getCheck_date()));
					cdate.setParent(item);	
					
					Listcell price = new Listcell();
					price.setLabel(String.valueOf(form.getPrice()));
					price.setParent(item);	
					
					Listcell type = new Listcell();
					type.setLabel(form.getType_name());
					type.setAttribute("pid", form.getType());
					type.setParent(item);	
					
					Listcell project = new Listcell();
					project.setLabel(form.getProject_name());
					project.setParent(item);	
					
					Listcell projectset = new Listcell();
					projectset.setLabel(form.getProjectset_name());
					projectset.setAttribute("pid", form.getProjectset_id());
					projectset.setParent(item);	
					
					Listcell has_data = new Listcell();
					if(form.isHas_data()){
						Button btn=new Button();
						btn.setLabel("下载");
						btn.setAttribute("pid", form.getPid());
						btn.setAttribute("serial", form.getSerial_num());
						btn.addEventListener("onClick", new EventListener(){
							public void onEvent(Event event) throws Exception {
								int value=(Integer) event.getTarget().getAttribute("pid");
								Map map=(Map)dbSession().queryForObject("Agreement.getAgreementData",value);
								byte[] data=(byte[])map.get("data");
								InputStream ins = new ByteArrayInputStream(data);
								Filedownload.save(ins, "doc", "hetong-"+event.getTarget().getAttribute("serial")+".doc");
							}
						});
						btn.setParent(has_data);
					}else{
						has_data.setLabel("无资料");
					}
					has_data.setParent(item);	
					
					Listcell pid = new Listcell();
					pid.setLabel(String.valueOf(form.getPid()));
					pid.setParent(item);
					pid.setVisible(false);
				}		
			};
	}
	
	public void onEdit(){
		String value=lb.getPKListcellValue(this, "grid");
		if(value!=null){
			try {
				final int key =Integer.parseInt(value);
				final Window win=(Window)Executions.createComponents(getPagefileSession()+"edit.zul", null, null);
				final UtilZKObject zobj= new UtilZKObject(win);
				Events.postEvent("onModal", win, null);
				((Listbox)win.getFellow("ed_projectset")).setDisabled(true);
				setListData(win);
				setEditdata(zobj);
				win.getFellow("btn_upload").addEventListener("onUpload", new EventListener(){
					public void onEvent(Event e) throws Exception {
						UploadEvent evt=(UploadEvent)e;
						if(win.getFellow("vbox_fileList").getChildren().size()>0)win.getFellow("vbox_fileList").getFirstChild().detach();
						Media[] medias=null;	
						medias = evt.getMedias();
						upload(medias,win);
					}
				});
				win.getFellow("ed_project").addEventListener("onSelect", new EventListener(){
					public void onEvent(Event event) throws Exception {
						Listbox lb=(Listbox) win.getFellow("ed_project");
						if(lb.getSelectedItem().getValue()!=null){
							setListProsetData(win,Integer.parseInt(zobj.getObjectValue(lb)));
						}
						
					}
				});
				win.getFellow("ed_submit").addEventListener("onClick", new EventListener(){
					public void onEvent(Event event) throws Exception {
						A_project sb=setBean(zobj);
						sb.setPid(key);
						dbSession().update("Agreement.updateAgreement", sb);
						Messagebox.show("修改完毕");
						win.detach();
						initialize();
					}
				});
				win.getFellow("ed_cancel").addEventListener("onClick",new EventListener(){
					public void onEvent(Event event) throws Exception {
						win.detach();
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
	}
	public void onDelete(){
		String value=lb.getPKListcellValue(this, "grid");
		if(value!=null){
			int key =Integer.parseInt(value);
			try {
				if(Messagebox.show("删除可能造成系统混乱", "注意", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION )==Messagebox.YES){
					dbSession().delete("Agreement.deleteAgreement",key);
					initialize();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public void onAdd() {
		final Window win=(Window)Executions.createComponents(getPagefileSession()+"edit.zul", null, null);
		final UtilZKObject zobj= new UtilZKObject(win);
		win.setTitle("新增資料");
		Events.postEvent("onModal", win, null);
		setListData(win);
		((Listbox)win.getFellow("ed_projectset")).setDisabled(true);
		win.getFellow("person").setVisible(false);
		Listbox slb=(Listbox)win.getFellow("ed_signer");
		for(Object obj:slb.getChildren()){
			if(((Listitem)obj).getValue()!=null&&Integer.parseInt((String)((Listitem)obj).getValue())==getUserPid()){
				slb.setSelectedItem(((Listitem)obj));
			}
		}
		win.getFellow("btn_upload").addEventListener("onUpload", new EventListener(){
			public void onEvent(Event e) throws Exception {
				UploadEvent evt=(UploadEvent)e;
				if(win.getFellow("vbox_fileList").getChildren().size()>0)win.getFellow("vbox_fileList").getFirstChild().detach();
				Media[] medias=null;	
				medias = evt.getMedias();
				upload(medias,win);
			}
		});
		win.getFellow("ed_project").addEventListener("onSelect", new EventListener(){
			public void onEvent(Event event) throws Exception {
				Listbox lb=(Listbox) win.getFellow("ed_project");
				if(lb.getSelectedItem().getValue()!=null){
					setListProsetData(win,Integer.parseInt(zobj.getObjectValue(lb)));
				}
			}
		});
		win.getFellow("ed_submit").addEventListener("onClick", new EventListener(){
			public void onEvent(Event event) throws Exception {
				dbSession().update("Agreement.insertAgreement", setBean(zobj));
				Messagebox.show("新增完畢");
				win.detach();
				initialize();
			}
		});
		win.getFellow("ed_cancel").addEventListener("onClick",new EventListener(){
			public void onEvent(Event event) throws Exception {
				win.detach();
			}
		});
	}
	private void upload(Media[] medias,Component component){
	    for(Media obj : medias){
	      String name[]=obj.getName().split("\\.");
	      if(!(name[name.length-1].equals("doc")||name[name.length-1].equals("doc"))){
	    	  new Label("檔案格式錯誤,接受doc格式").setParent(component.getFellow("vbox_fileList"));
	    	  break;
	      }
	      byte[] file_byte=null;
	      //用來記錄檔案的大小
	      int size = 0;
	      //檔案的IO處理,將檔案從media透過inputstream 和outputstream來做傳輸
	      try {
	        //FileOutputStream fos = new FileOutputStream(new File(uploadFolderPath + obj.getName()));
	    	ByteArrayOutputStream bos=new ByteArrayOutputStream();
	        InputStream is = obj.getStreamData();
	        byte[] buffer = new byte[1024];
	        int pointer = 0;
	        while((pointer = is.read(buffer))!= -1){
	          size += pointer;
	          bos.write(buffer, 0, pointer);
	        }
	        if(is != null){
	          is.close();
	        }
	        if(bos != null){
	        	file_byte=bos.toByteArray();
	        	bos.flush();
	        	bos.close();
	        }
	      } catch (Exception e) {
	    	 new Label("上传失败,檔案可能過大").setParent(component.getFellow("vbox_fileList"));
	        e.printStackTrace();
	      } 
	      Hbox hb = new Hbox();
	      hb.setAttribute("data", file_byte);
	      hb.setParent(component.getFellow("vbox_fileList"));
	      Toolbarbutton tbb = new Toolbarbutton();
	      tbb.setLabel(obj.getName());
	      tbb.setHref(obj.getName());
	      tbb.setParent(hb);
	      Label lb = new Label();
	      lb.setValue(size/1024 + " KB");
	      lb.setParent(hb);
	    }
	  }
	public void setEditdata(UtilZKObject zobj){
		zobj.setObjectValue("ed_serial_num", lb.getListcellValue(this, "grid", 0));
		zobj.setObjectValue("ed_name", lb.getListcellValue(this, "grid", 1));
		zobj.setObjectValue("ed_subcontractor", lb.getListcellAttributeValue(this, "grid", 2,"pid"));
		zobj.setObjectValue("ed_note", lb.getListcellValue(this, "grid", 3));
		zobj.setObjectValue("ed_signer", lb.getListcellAttributeValue(this, "grid", 4,"pid"));
		zobj.setObjectValue("ed_sdate", lb.getListcellValue(this, "grid", 5));
		zobj.setObjectValue("ed_edate", lb.getListcellValue(this, "grid", 6));
		zobj.setObjectValue("ed_cdate", lb.getListcellValue(this, "grid", 7));
		zobj.setObjectValue("ed_price", lb.getListcellValue(this, "grid", 8));
		zobj.setObjectValue("ed_type", lb.getListcellAttributeValue(this, "grid", 9,"pid"));
		String projectset= lb.getListcellAttributeValue(this, "grid", 11,"pid");
		try {
			Projectset ps=(Projectset)dbSession().queryForObject("Projectset.getProset_byPro",Integer.parseInt(projectset));
			zobj.setObjectValue("ed_project", String.valueOf(ps.getProject_id()));
			setListProsetData((Window)zobj.getContrain(),ps.getProject_id());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		zobj.setObjectValue("ed_projectset", projectset);
	}
	public A_project setBean(UtilZKObject zobj) throws Exception{
		A_project sb= new A_project();
		sb.setName(zobj.getValue("ed_name"));
		sb.setSerial_num(zobj.getValue("ed_serial_num"));
		sb.setType(Integer.parseInt(zobj.getValue("ed_type")));
		sb.setNote(zobj.getValue("ed_note"));
		sb.setSigner(Integer.parseInt(zobj.getValue("ed_signer")));
		sb.setSubcontractor_id(Integer.parseInt(zobj.getValue("ed_subcontractor")));
		sb.setS_date((zobj.getValue("ed_sdate").equals(""))?null:new Date(sdf.parse(zobj.getValue("ed_sdate")).getTime()));
		sb.setE_date((zobj.getValue("ed_edate").equals(""))?null:new Date(sdf.parse(zobj.getValue("ed_edate")).getTime()));
		sb.setPrice(Integer.parseInt(zobj.getValue("ed_price")));
		sb.setProjectset_id(Integer.parseInt(zobj.getValue("ed_projectset")));
		sb.setData((byte[]) zobj.getContrain().getFellow("vbox_fileList").getFirstChild().getAttribute("data"));
		return sb;
	}
	public void setListProsetData(Window win,int value){
		((Listbox)win.getFellow("ed_projectset")).setDisabled(false);
		setList(win,"Projectset.select_List","ed_projectset",value);
	}
	public void setListProsetData(){
		String fellow=(String)((Listbox)getFellow("project")).getSelectedItem().getValue();
		int value=Integer.parseInt((fellow==null)?"0":fellow);
		setList(this,"Projectset.select_List","project_set",value);
	}
	public void setListData(Window win){
		setList(win,"Project.select_List","ed_project");
		setList(win,"Agreement_Type.select_List","ed_type");
		setList(win,"Subcontractor.select_List","ed_subcontractor");
		setList(win,"User.select_List","ed_signer");
	}
	public void setListData(){
		setList(this,"Project.select_List","project");
		setList(this,"Subcontractor.select_List","sub");
	}
	public void setSub(String text){
		Map<String, String> map =new HashMap<String, String>();
		map.put("name", (text.equals(""))?null:"%"+text+"%");
		setList(this,"Subcontractor.select_List","sub",map);
	}
	public String setDate(Date date){
		return date!=null?sdf.format(date):null;
	}
	private Date parserDate(String id) {
		try {
			return (ZKObj.getValue(id).equals(""))?null:new Date(sdf.parse(ZKObj.getValue(id)).getTime());
		} catch (ParseException e) {
			return null;
		}
	}
}